<?php

namespace App\Admin\Auth;

use App\admin\BaseController;
use App\Http\Models\AdminRole;
use App\Http\Models\AdminUser;
use App\Utils\Code;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

/**
 * 管理员控制器
 */
class AdminUserController extends BaseController
{
	
	/**
	 * 管理员列表显示
	 */	
	public function index()
	{
		$list = AdminUser::all()->toArray();
		$count = AdminUser::count();
		return view('admin/adminUser/index', ['list' => json_encode($list), 'count' => $count]);
	}

	/**
	 * 获取管理员列表
	 */	
	public function getList()
	{
		$list = AdminUser::all()->toArray();
		$count = AdminUser::count();
		return renderData(['list' => $list, 'count' => $count]);
	}

	/**
	 * 添加管理员显示
	 */
	public function edit($id = false)
	{
		$roleList = AdminRole::where(['status' => 1]) -> get() -> toArray();
		$admin = [];
		if ($id) $admin = AdminUser::find($id)->toArray();
		return view('admin/adminUser/edit', ['roleList' => $roleList, 'admin' => $admin]);
	}

	/**
	 * 保存管理员信息
	 */ 
	public function save(Request $request)
	{
		$data = $request->input();
		if (isset($data['id']) && $data['id']) {
			$sysAdmin = AdminUser::find($data['id']);
			$result = $sysAdmin->fill($data)->save(); 
		} else {
			$sysAdmin = new AdminUser;

			// 表单验证
			if (!isset($data['account']) || !$data['account']) return renderError(Code::PARAM_IS_ERROR);
			if (!isset($data['password']) || !$data['password']) return renderError(Code::PARAM_IS_ERROR);

			// 查询账号是否已存在
			$admin = AdminUser::where(['account' => $data['account']]) -> find(1);
			if ($admin) return renderError(Code::SAVE_EXISTS_FAILED);

			$data['password'] = Hash::make($data['password']);
			$result = $sysAdmin->fill($data)->save();
		}
		if ($result) {
			return renderSuccess('保存成功');
		}

		return renderError(Code::SAVE_FAILED);
		
	}


	/**
	 * 删除管理员
	 */

	public function delete($id)
	{
		$admin = AdminUser::find($id);
		if (!$admin) return renderError(Code::DELETE_FAILED);
		if ($admin->delete()) {
			return renderSuccess('删除成功');
		}
		return renderError(Code::DELETE_FAILED);
	}

}